<template>
  <div>
    <!-- 查询区域 -->
    <div class="card" style="margin-bottom: 5px">
      <el-card>
        <el-input
            style="width: 200px; margin-right: 10px"
            v-model="a_equipment.name"
            placeholder="请输入设备名称查询"
            prefix-icon="Search"
        />
        <el-input
            style="width: 200px; margin-right: 10px"
            v-model="a_equipment.id"
            placeholder="请输入设备ID查询"
            prefix-icon="Search"
        />
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="warning" @click="reset">重 置</el-button>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table
          :data="a_equipment.tableData"
          border
          style="width: 100%"
          stripe
          @selection-change="handleSelectionChange"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55"/>

        <!-- 序号列 -->
        <el-table-column label="编号" type="index" width="60"/>

        <!-- 设备ID -->
        <el-table-column label="设备ID" prop="seid"/>
        <!-- 设备名称 -->
        <el-table-column label="设备名称" prop="sname"/>
        <!-- 设备状态 -->
        <el-table-column label="设备状态">
          <template #default="scope">
            {{ scope.row.condition == 1 ? '正常' : '故障' }}
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <div>
              <el-button
                  type="primary"
                  :icon="Edit"
                  size="small"
                  @click="handleEdit(scope.row)"
              >编 辑
              </el-button>
            </div>
            <el-button
                type="danger"
                :icon="Delete"
                size="small"
                @click="handleDelete(scope.row)"
            >删 除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="a_equipment.pageNumber"
            v-model:page-size="a_equipment.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="a_equipment.total"
            background
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="a_equipment.form.seid ? '编辑设备' : '新增设备'"
        v-model="a_equipment.formVisible"
        width="500"
    >
      <el-form :model="a_equipment.form" style="padding-right: 50px; padding-top: 20px;">
        <el-form-item label="设备名称" label-width="80px">
          <el-input v-model="a_equipment.form.sname" placeholder="请输入设备名称"/>
        </el-form-item>
        <el-form-item label="设备状态" label-width="80px">
          <el-select v-model="a_equipment.form.condition" placeholder="请选择状态">
            <el-option label="正常" value="1"/>
            <el-option label="故障" value="0"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="a_equipment.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive} from 'vue'
import request from '@/utils/request'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Edit, Delete} from '@element-plus/icons-vue'

// 正确导入
import {useRoute} from 'vue-router'
import {onMounted} from 'vue'

const a_equipment = reactive({
  name: '',
  id: '',
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  tableData: [],
  formVisible: false,
  form: {},
  selectedRows: []
})

// 加载数据
const load = () => {
  request.get('/v1/admin/selectPage', {
    params: {
      tableName: 'equipment',
      name: a_equipment.name,
      id: a_equipment.id,
      pageNum: a_equipment.pageNumber,
      pageSize: a_equipment.pageSize
    }
  }).then(res => {
    if (res.state === 2001) {
      a_equipment.tableData = res.data.list || []
      a_equipment.total = res.data.total || 0
    } else {
      a_equipment.tableData = []
      a_equipment.total = 0
    }
  }).catch(error => {
    console.error('请求失败:', error)
    a_equipment.tableData = []
    a_equipment.total = 0
  })
}

// 重置查询条件
const reset = () => {
  a_equipment.name = ''
  a_equipment.id = ''
  load()
}

// 处理新增
const handleAdd = () => {
  a_equipment.form = {
    sname: '',
    condition: ''
  }
  a_equipment.formVisible = true
}

// 处理编辑
const handleEdit = (row) => {
  a_equipment.form = {...row}
  a_equipment.formVisible = true
}

// 处理单个删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该设备吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/delete', {
      data: {
        tableName: 'equipment',
        id: row.seid
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({message: '删除成功', type: 'success'})
        load()
      } else {
        ElMessage({message: '删除失败', type: 'error'})
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({message: '请求失败，请检查网络或服务器', type: 'error'})
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  if (a_equipment.selectedRows.length === 0) {
    ElMessage.warning('请选择要删除的设备')
    return
  }

  const ids = a_equipment.selectedRows.map(row => row.seid)

  ElMessageBox.confirm('确定要删除这些设备吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/batchDelete', {
      data: {
        tableName: 'equipment',
        ids: ids
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error('批量删除失败')
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage.error('请求失败，请检查网络或服务器')
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理表格多选变化
const handleSelectionChange = (rows) => {
  a_equipment.selectedRows = rows
}

// 保存新增或编辑
const save = () => {
  const method = a_equipment.form.seid ? 'put' : 'post'
  const url = a_equipment.form.seid ? '/v1/admin/update' : '/v1/admin/add'
  // 将 condition 从字符串转为整数
  console.log("a_equipment.form.condition.value:", a_equipment.form.condition)
  const submitData = {
    ...a_equipment.form,
    condition: a_equipment.form.condition == 1,
  }
  console.log("submitData.condition:", submitData.condition)
  request[method](url, {
    tableName: 'equipment',
    data: submitData
  }).then(res => {
    console.log("res:", res)
    if (res.state === 2001) {
      ElMessage({
        message: a_equipment.form.seid ? '编辑成功' : '新增成功',
        type: 'success'
      })
      a_equipment.formVisible = false
      load()
    } else {
      ElMessage({
        message: a_equipment.form.seid ? '编辑失败' : '新增失败',
        type: 'error'
      })
    }
  }).catch(error => {
    console.error('请求失败:', error)
    ElMessage({message: '请求失败，请检查网络或服务器', type: 'error'})
  })
}


// 初始化加载数据
load()

// 路由参数处理（可选）
const route = useRoute()
onMounted(() => {
  const seid = route.params.seid
  if (seid) {
    a_equipment.id = seid
    load()
  }
})
</script>

<style scoped>
.card {
  margin-bottom: 10px;
}
</style>
